package alpha.com.google.code.mechanic.janitor.ui.handler;


import java.io.File;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import alpha.com.google.code.mechanic.janitor.controller.ContextData;
import alpha.com.google.code.mechanic.janitor.controller.ZipFiles;
import alpha.com.google.code.mechanic.janitor.model.ContextsCollector;
import alpha.com.google.code.mechanic.janitor.model.IContext;
import alpha.com.google.code.mechanic.janitor.ui.ExportContextDialog;

/**
 * The class is to handle the command of the menu item "Export". The command
 * allows users export configuration files of one or multiple Contexts at one
 * time, and compress the them as Context_Name.zip files. 
 * 
 * Last_edited: Oct 29, 2014
 * 
 * @author jingjiejiang
 * @since Oct 15, 2014
 */
public class ExportHandler extends AbstractHandler {

  public Object execute(ExecutionEvent event) throws ExecutionException {
    
    Shell pshell = Display.getCurrent().getActiveShell();
    
    ContextData data = new ContextData();
    ContextsCollector contexts = new ContextsCollector(); 
    
    try {
      if (data.readContextsFile()) {
        contexts = data.getContextsCollector();
      }
      
    } catch (Exception e) {
      MessageDialog.openError(pshell, "Couldn't get the Contexts data from "
          + " context.con file", e.getMessage());
    }
    
    ExportContextDialog dialog = new ExportContextDialog(pshell, contexts.getContextList());
    
    int dialogopen = dialog.open();
    if (Dialog.OK == dialogopen) {
      
      List<IContext> selctxs = dialog.getSelContexts();
      String dstndir = dialog.getDstnDir();
      
      for (IContext context : selctxs){
        
        String zipfile = dstndir + File.separator + context.getName() + ".zip";
        ZipFiles zip = new ZipFiles(context.getFileLocation(), zipfile);
        zip.zipFiles();
      }
      
      dialog.close();
    } 
    else if (Dialog.CANCEL == dialogopen) {
      dialog.close();
    }
    
    return null;
  }

}
